﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace ProgramCat.FiddlerExtension.Core.Utils.UiEx
{
    /// <summary>
    /// 文本框扩展 字符选中事件
    /// </summary>
    public class TextBoxEx
    {
        private bool isMouseDown = false;
        Action<int> action = null;
        private int selectedTextLenght = -1;
        TextBox textBox = null;
        public TextBoxEx(TextBox textBox, Action<int> action)
        {
            if (textBox != null)
            {
                this.action = action;
                this.textBox = textBox;
                this.textBox.KeyDown += OnKeyDown;

                this.textBox.LostFocus += (sender, e) =>
                {
                    selectedTextLenght = 0;
                    action?.Invoke(selectedTextLenght);
                    isMouseDown = false;
                };
                this.textBox.GotFocus += (sender, e) =>
                {
                    if (textBox.SelectionLength != 0)
                    {
                        action?.Invoke(textBox.SelectionLength);
                    }
                };


                this.textBox.MouseDown += (sender, e) =>
                {
                    selectedTextLenght = 0;
                    action?.Invoke(selectedTextLenght);
                    isMouseDown = true;

                };
                this.textBox.MouseUp += (sender, e) =>
                {
                    isMouseDown = false;

                };
                this.textBox.MouseMove += OnMouseMove;
            }
        }

       

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                if (selectedTextLenght != textBox.SelectionLength)
                {
                    selectedTextLenght = textBox.SelectionLength;
                    action?.Invoke(selectedTextLenght);
                }
            }
        }

        private async void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Shift)
            {
                await Task.Delay(10);
                if (selectedTextLenght != textBox.SelectionLength)
                {
                    selectedTextLenght = textBox.SelectionLength;
                    action?.Invoke(selectedTextLenght);
                } 
            }
           
        }
    }

    public static class TextBoxHelp
    {
        public static TextBoxEx AddSelectionChanged(this TextBox textBox, Action<int> onSelectionChanged)
        {
            return new TextBoxEx(textBox, onSelectionChanged);
        }

    } 
}
